<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input style="width: 200px;" class="filter-item" placeholder="编码" v-model="listQuery.code">
            </el-input>
            <el-input style="width: 200px;" class="filter-item" placeholder="名称" v-model="listQuery.name">
            </el-input>
            <el-input style="width: 200px;" class="filter-item" placeholder="URL" v-model="listQuery.url">
            </el-input>
            <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>

            <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>
            
            <el-button class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus">新增权限</el-button>
        </div>

        <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row style="width: 100%">
            <el-table-column align="center" :label="$t('table.id')" width="65">
                <template slot-scope="scope">
                    <span>{{scope.$index+1}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="编码">
                <template slot-scope="scope">
                    <span>{{scope.row.code}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="名称">
                <template slot-scope="scope">
                    <span>{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="URL">
                <template slot-scope="scope">
                    <span>{{scope.row.url}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" :label="$t('table.actions')" width="360" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="info" size="mini" @click="handleInfo(scope.row,'info')">{{$t('table.info')}}</el-button>
                    <el-button size="mini" type="danger" @click="handleDelete(scope.row,'deleted')">{{$t('table.delete')}}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit" layout="total, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 400px; margin-left:50px;'>
                <el-form-item label="编码" prop="code" v-if="dialogStatus==='info'">
                  <span v-if="dialogStatus!=='create'">{{temp.code}}</span>
                    <el-input v-else v-model="temp.code"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                  <span v-if="dialogStatus!=='create'">{{temp.name}}</span>
                    <el-input v-else v-model="temp.name"></el-input>
                </el-form-item>
                <el-form-item label="URL" prop="url">
                  <span v-if="dialogStatus!=='create'">{{temp.url}}</span>
                    <el-input v-else v-model="temp.url"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer" v-if="dialogStatus !== 'info'">
                <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
                <el-button type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import {
  fetchList,
  infoSysAuth,
  createSysAuth,
  deleteSysAuth
} from '@/api/user/sysAuth'
import waves from '@/directive/waves' // 水波纹指令
import { parseTime } from '@/utils'

export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    const validateAuthUri = (rule, value, callback) => {
      const urlregex = /\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(do))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/

      if (value) {
        if (urlregex.test(value)) {
          callback()
        } else {
          callback('url格式填写不正确(/aa/a.do)')
        }
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      page: {
        page: 1,
        limit: 20,
        sort: ''
      },
      listQuery: {
        code: undefined,
        name: undefined,
        url: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        info: '详情'
      },
      temp: {
        code: '',
        name: '',
        url: ''
      },
      rules: {
        code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        url: [{ required: true, message: 'URL不能为空', trigger: 'blur' }, { validator: validateAuthUri, trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  filters: {},
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.content.list
        this.total = response.content.total
        this.listLoading = false
      })
    },
    // 搜索按钮
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 跳转页数
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 详情
    handleInfo(row, status) {
      infoSysAuth(row.id).then(response => {
        if (response.success) {
          this.temp = Object.assign({}, response.content) // copy obj
          this.dialogStatus = status
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        }
      })
    },
    resetTemp() {
      this.temp = {
        code: '',
        name: '',
        url: ''
      }
    },
    // 打开新增dialog
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 新增数据post
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createSysAuth(this.temp).then(response => {
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            }
          })
        }
      })
    },
    // 删除操作
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 调用删除接口
          var p = { id: row.id }
          deleteSysAuth(p).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    restQuery() {
      this.listQuery.expireStatus = ''
      this.listQuery.balanceType = ''
      this.listQuery.contractStatus = ''
      this.listQuery.compoundSearch = ''
      this.getList()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
